<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Promise中提炼异步任务</title>
</head>
<body>
  <button onclick="userLogin()">用户登录</button>
  <div>
    <p id="welcome"></p>
    <ul id="friends"></ul>
  </div>
</body>
<script src="./js/jquery.min.js"></script>
<script>

  // 1. 定义请求ajax功能函数
  function myAjax(url, type, data, success, fail) {
    if (!url || !type) {
      console.log('请求参数缺省');
      return;
    }

    $.ajax({
      type: type,
      url: url,
      data: data,
      dataType: 'json',
      success: function(data){
        success(data);
      },
      error: function(xhr, type){
        fail(xhr, type);
      }
    });
  }

  // 2.封装Promise对象
  function getPromise(url, type, data){
    return new Promise((resolve, reject) => {
      myAjax(url, type, data, (data) => {
        // 数据请求成功了 request 非4xx和5xx（400，404，500，502）
        // 1. 真成功
        // 2. 不是想要的成功的数据（数据异常）
        // 何如解决？（前后端协商好状态码， code 200 真成功 201-20x假成功）
        if(data.code == 200){
          resolve(data);
        } else {
          reject({code:data.code, msg:data.msg})
        }
      }, (xhr, type) => {
        reject({code: 300, type: type});
      });
    });
  }
  /*
  function userLogin(){
    let req1 = "http://127.0.0.1:3000/user/login";
    let uData = {uname: 'Jack', upwd: '123456'};
    getPromise(req1, 'POST', uData).then(data => {
      console.log(data);
      // DOM操作
      let show = document.querySelector("#welcome");
      show.innerHTML = `${data.msg},欢迎${uData.uname}登录`;

      let token = data.token;
      let url_string = `http://127.0.0.1:3000/user/friends?token=${token}`;
      return getPromise(url_string, 'GET', {});
    }).then(data => {
      console.log(data);
      let ul_list = document.querySelector("#friends");
      for(let i = 0; i < data.data.length; i++){
        let el = document.createElement("li");
        el.innerText = `${data.data[i].name} : ${data.data[i].age}.`;
        ul_list.appendChild(el);
      }
    }).catch( err => {
      console.log(err);
    });
  }
  */

  // 定义 async 功能函数
  async function request(){
    let request1 = `http://127.0.0.1:3000/user/login`;
    let data1 = {uname: 'Jack', upwd: '123456'};
    let res1 = await getPromise(request1, 'POST', data1);
    console.log('1:',res1);
    // DOM操作
    let show = document.querySelector("#welcome");
    show.innerHTML = `${res1.msg},欢迎${data1.uname}登录`;

    if (res1.code == 200) {
      let request2 = `http://127.0.0.1:3000/user/friends?token=${res1.token}`
      let res2 = await getPromise(request2, 'GET', {});
      console.log('2:', res2);
      let ul_list = document.querySelector("#friends");
      for(let i = 0; i < res2.data.length; i++){
        let el = document.createElement("li");
        el.innerText = `${res2.data[i].name} : ${res2.data[i].age}.`;
        ul_list.appendChild(el);
      }
    } else {
      console.log(res1.code);
    }
  }

  function userLogin(){
    request();
  }
</script>
</html>